package cn.labbook.bluetooth.exception;


import cn.labbook.bluetooth.constant.ResultConstant;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 2018/4/12.
 * Description : 自定义异常解析
 */
@Log4j2
public class SysExceptionResolver implements HandlerExceptionResolver {


    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Object o, Exception ex) {

        ModelAndView resultView = new ModelAndView();
        //判断是否是ajax请求
        if (isAjax(request)) {
            FastJsonJsonView jsonView = new FastJsonJsonView();
            jsonView.setAttributesMap(errorJsonResult(ex));
            resultView.setView(jsonView);
        } else {
            resultView.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
            resultView.setViewName("error");
            log.error("发生异常!异常信息为:", ex);
        }
        return resultView;
    }

    public static boolean isAjax(HttpServletRequest request) {
        String requestType = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equalsIgnoreCase(requestType);
    }

    public static Map<String, Object> errorJsonResult(Exception e) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", ResultConstant.FAIL_CODE);
        if (e instanceof SysException || e instanceof SysAuthException) {
            result.put("msg", e.getMessage());
            log.error(e);
        } else {
            result.put("msg", "未知错误");
            log.error("发生异常!异常信息为:", e);
        }
        return result;
    }
}
